import React, { useState, useEffect } from 'react';
import { Card, Button, Space, Tag, Modal, message, Form, Input, Select, Row, Col, Divider } from 'antd';
import { 
  PlusOutlined, 
  SearchOutlined, 
  ReloadOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  ExclamationCircleOutlined,
  SettingOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { CustomTable } from '../../g-component/CustomTable';
import { User } from '../../g-types/user';
import { UserListApi } from './server';
import './index.less';

const { confirm } = Modal;
const { Option } = Select;

/**
 * 用户状态标签
 */
const UserStatusTag: React.FC<{ status?: number }> = ({ status }) => {
  if (status === 0) {
    return <Tag color="error">禁用</Tag>;
  }
  return <Tag color="success">启用</Tag>;
};

/**
 * 性别展示
 */
const GenderText: React.FC<{ gender?: number }> = ({ gender }) => {
  switch (gender) {
    case 1:
      return <span>男</span>;
    case 2:
      return <span>女</span>;
    default:
      return <span>未知</span>;
  }
};

// 搜索条件接口
interface SearchParams {
  page?: number;
  pageSize?: number;
  keyword?: string;
  username?: string;
  nickname?: string;
  email?: string;
  phone?: string;
  department?: string;
  position?: string;
  status?: number;
  [key: string]: string | number | undefined;
}

// 搜索配置接口
interface SearchConfigType {
  username: boolean;
  nickname: boolean;
  email: boolean;
  phone: boolean;
  department: boolean;
  position: boolean;
  status: boolean;
}

/**
 * 用户列表内容组件 - 不包含布局
 */
export const UserListContent: React.FC = () => {
  // 用户列表数据
  const [userList, setUserList] = useState<User[]>([]);
  // 加载状态
  const [loading, setLoading] = useState<boolean>(false);
  // 分页信息
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  
  // 搜索表单
  const [searchForm] = Form.useForm();
  
  // 编辑用户的表单
  const [editForm] = Form.useForm();
  
  // 是否显示编辑Modal
  const [editModalVisible, setEditModalVisible] = useState<boolean>(false);
  
  // 是否显示搜索项配置Modal
  const [searchConfigVisible, setSearchConfigVisible] = useState<boolean>(false);
  
  // 当前编辑的用户
  const [currentUser, setCurrentUser] = useState<User | null>(null);

  // 搜索条件
  const [searchParams, setSearchParams] = useState<SearchParams>({});

  // 搜索字段显示配置
  const [searchConfig, setSearchConfig] = useState<SearchConfigType>({
    username: true,
    nickname: true,
    email: true,
    phone: true,
    department: true,
    position: true,
    status: true,
  });

  // 获取用户列表
  const fetchUserList = async (page = pagination.current, pageSize = pagination.pageSize, params = searchParams) => {
    try {
      setLoading(true);
      const result = await UserListApi.getUserList({
        page,
        pageSize,
        ...params,
      });
      setUserList(result.list);
      setPagination({
        ...pagination,
        current: page,
        total: result.total,
      });
    } catch (error) {
      console.error('获取用户列表失败', error);
      message.error('获取用户列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 初始化加载数据
  useEffect(() => {
    fetchUserList();
  }, []);

  // 处理表格变更
  const handleTableChange = (page: number, pageSize?: number) => {
    fetchUserList(page, pageSize);
  };

  // 处理搜索
  const handleSearch = (values: SearchParams) => {
    // 过滤掉空值
    const params = Object.keys(values).reduce((result, key) => {
      const k = key as keyof SearchParams;
      if (values[k] !== undefined && values[k] !== null && values[k] !== '') {
        result[k] = values[k];
      }
      return result;
    }, {} as SearchParams);
    
    setSearchParams(params);
    fetchUserList(1, pagination.pageSize, params);
  };

  // 重置搜索
  const handleResetSearch = () => {
    searchForm.resetFields();
    setSearchParams({});
    fetchUserList(1, pagination.pageSize, {});
  };

  // 处理添加用户
  const handleAddUser = () => {
    setCurrentUser(null);
    editForm.resetFields();
    setEditModalVisible(true);
  };

  // 处理编辑用户
  const handleEditUser = (user: User) => {
    setCurrentUser(user);
    editForm.setFieldsValue({
      username: user.username,
      nickname: user.nickname,
      email: user.email,
      phone: user.phone,
      gender: user.gender,
      department: user.department,
      position: user.position,
      role: user.role,
      status: user.status,
    });
    setEditModalVisible(true);
  };

  // 处理删除用户
  const handleDeleteUser = (user: User) => {
    confirm({
      title: '确定要删除此用户吗?',
      icon: <ExclamationCircleOutlined />,
      content: '删除后无法恢复',
      onOk: async () => {
        try {
          await UserListApi.deleteUser(user.id);
          message.success('删除成功');
          fetchUserList();
        } catch (error) {
          console.error('删除用户失败', error);
          message.error('删除用户失败');
        }
      },
    });
  };

  // 保存用户信息
  const handleSaveUser = async () => {
    try {
      const values = await editForm.validateFields();
      if (currentUser) {
        // 编辑用户
        await UserListApi.updateUser({
          id: currentUser.id,
          ...values,
        });
        message.success('更新用户成功');
      } else {
        // 新增用户
        await UserListApi.createUser(values);
        message.success('创建用户成功');
      }
      setEditModalVisible(false);
      fetchUserList();
    } catch (error) {
      console.error('保存用户失败', error);
      message.error('保存用户失败');
    }
  };

  // 保存搜索项配置
  const handleSaveSearchConfig = (newConfig: SearchConfigType) => {
    setSearchConfig(newConfig);
    setSearchConfigVisible(false);
  };

  // 表格列定义
  const columns: ColumnsType<User> = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      width: 120,
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
      key: 'nickname',
      width: 120,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      width: 180,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      width: 140,
    },
    {
      title: '性别',
      dataIndex: 'gender',
      key: 'gender',
      width: 80,
      render: (gender?: number) => <GenderText gender={gender} />,
    },
    {
      title: '部门',
      dataIndex: 'department',
      key: 'department',
      width: 120,
    },
    {
      title: '职位',
      dataIndex: 'position',
      key: 'position',
      width: 120,
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      width: 120,
      render: (role?: string | string[]) => {
        if (!role) return '-';
        if (typeof role === 'string') return role;
        return role.join(', ');
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status?: number) => <UserStatusTag status={status} />,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 120,
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right' as const,
      width: 120,
      render: (_: unknown, record: User) => (
        <Space size="middle">
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            size="small"
            onClick={() => handleEditUser(record)}
          >
            编辑
          </Button>
          <Button 
            type="link" 
            danger
            icon={<DeleteOutlined />} 
            size="small"
            onClick={() => handleDeleteUser(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div className="user-list-container">
      <h2 className="page-title">用户管理</h2>

      {/* 搜索区域 */}
      <Card bordered={false} className="search-card">
        <Form
          form={searchForm}
          name="userSearchForm"
          layout="horizontal"
          onFinish={handleSearch}
        >
          <Row gutter={[16, 16]}>
            {searchConfig.username && (
              <Col span={6}>
                <Form.Item name="username" label="用户名">
                  <Input placeholder="请输入用户名" allowClear />
                </Form.Item>
              </Col>
            )}
            
            {searchConfig.nickname && (
              <Col span={6}>
                <Form.Item name="nickname" label="昵称">
                  <Input placeholder="请输入昵称" allowClear />
                </Form.Item>
              </Col>
            )}
            
            {searchConfig.email && (
              <Col span={6}>
                <Form.Item name="email" label="邮箱">
                  <Input placeholder="请输入邮箱" allowClear />
                </Form.Item>
              </Col>
            )}
            
            {searchConfig.phone && (
              <Col span={6}>
                <Form.Item name="phone" label="手机号">
                  <Input placeholder="请输入手机号" allowClear />
                </Form.Item>
              </Col>
            )}
            
            {searchConfig.department && (
              <Col span={6}>
                <Form.Item name="department" label="部门">
                  <Input placeholder="请输入部门" allowClear />
                </Form.Item>
              </Col>
            )}
            
            {searchConfig.position && (
              <Col span={6}>
                <Form.Item name="position" label="职位">
                  <Input placeholder="请输入职位" allowClear />
                </Form.Item>
              </Col>
            )}
            
            {searchConfig.status && (
              <Col span={6}>
                <Form.Item name="status" label="状态">
                  <Select placeholder="请选择状态" allowClear>
                    <Option value={1}>启用</Option>
                    <Option value={0}>禁用</Option>
                  </Select>
                </Form.Item>
              </Col>
            )}
            
            <Col span={24}>
              <div className="table-toolbar">
                <Space>
                  <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                    搜索
                  </Button>
                  <Button onClick={handleResetSearch} icon={<ReloadOutlined />}>
                    重置
                  </Button>
                </Space>
                <Space>
                  <Button 
                    type="primary" 
                    icon={<PlusOutlined />}
                    onClick={handleAddUser}
                  >
                    新增用户
                  </Button>
                  <Button 
                    icon={<SettingOutlined />} 
                    onClick={() => setSearchConfigVisible(true)}
                  >
                    配置
                  </Button>
                </Space>
              </div>
            </Col>
          </Row>
        </Form>
      </Card>

      <Divider style={{ margin: '8px 0' }} />

      {/* 表格区域 */}
      <Card bordered={false} className="table-card">
        <CustomTable<User>
          columns={columns}
          dataSource={userList}
          rowKey="id"
          loading={loading}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            onChange: handleTableChange,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
          }}
          scroll={{ x: 1400 }}
        />
      </Card>

      {/* 编辑用户弹窗 */}
      <Modal
        title={currentUser ? '编辑用户' : '新增用户'}
        open={editModalVisible}
        onOk={handleSaveUser}
        onCancel={() => setEditModalVisible(false)}
        maskClosable={false}
        destroyOnClose
        width={600}
      >
        <Form
          form={editForm}
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 19 }}
          layout="horizontal"
        >
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>
          
          {!currentUser && (
            <Form.Item
              name="password"
              label="密码"
              rules={[{ required: true, message: '请输入密码' }]}
            >
              <Input.Password placeholder="请输入密码" />
            </Form.Item>
          )}
          
          <Form.Item
            name="nickname"
            label="昵称"
          >
            <Input placeholder="请输入昵称" />
          </Form.Item>
          
          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { type: 'email', message: '请输入有效的邮箱' }
            ]}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>
          
          <Form.Item
            name="phone"
            label="手机号"
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>
          
          <Form.Item
            name="gender"
            label="性别"
          >
            <Select placeholder="请选择性别">
              <Option value={0}>未知</Option>
              <Option value={1}>男</Option>
              <Option value={2}>女</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="department"
            label="部门"
          >
            <Input placeholder="请输入部门" />
          </Form.Item>
          
          <Form.Item
            name="position"
            label="职位"
          >
            <Input placeholder="请输入职位" />
          </Form.Item>
          
          <Form.Item
            name="role"
            label="角色"
          >
            <Select placeholder="请选择角色" mode="multiple">
              <Option value="admin">管理员</Option>
              <Option value="editor">编辑</Option>
              <Option value="viewer">访客</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="status"
            label="状态"
          >
            <Select placeholder="请选择状态">
              <Option value={1}>启用</Option>
              <Option value={0}>禁用</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      {/* 搜索项配置弹窗 */}
      <Modal
        title="搜索项配置"
        open={searchConfigVisible}
        onOk={() => handleSaveSearchConfig(searchConfig)}
        onCancel={() => setSearchConfigVisible(false)}
        destroyOnClose
      >
        <Form layout="vertical">
          <Row gutter={[16, 0]}>
            <Col span={8}>
              <Form.Item label="用户名">
                <Select 
                  value={searchConfig.username} 
                  onChange={(value) => setSearchConfig({...searchConfig, username: value})}
                >
                  <Option value={true}>显示</Option>
                  <Option value={false}>隐藏</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="昵称">
                <Select 
                  value={searchConfig.nickname} 
                  onChange={(value) => setSearchConfig({...searchConfig, nickname: value})}
                >
                  <Option value={true}>显示</Option>
                  <Option value={false}>隐藏</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="邮箱">
                <Select 
                  value={searchConfig.email} 
                  onChange={(value) => setSearchConfig({...searchConfig, email: value})}
                >
                  <Option value={true}>显示</Option>
                  <Option value={false}>隐藏</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="手机号">
                <Select 
                  value={searchConfig.phone} 
                  onChange={(value) => setSearchConfig({...searchConfig, phone: value})}
                >
                  <Option value={true}>显示</Option>
                  <Option value={false}>隐藏</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="部门">
                <Select 
                  value={searchConfig.department} 
                  onChange={(value) => setSearchConfig({...searchConfig, department: value})}
                >
                  <Option value={true}>显示</Option>
                  <Option value={false}>隐藏</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="职位">
                <Select 
                  value={searchConfig.position} 
                  onChange={(value) => setSearchConfig({...searchConfig, position: value})}
                >
                  <Option value={true}>显示</Option>
                  <Option value={false}>隐藏</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="状态">
                <Select 
                  value={searchConfig.status} 
                  onChange={(value) => setSearchConfig({...searchConfig, status: value})}
                >
                  <Option value={true}>显示</Option>
                  <Option value={false}>隐藏</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </div>
  );
}; 